// pages/order/order.js
var Zan = require('../../../dist/index.js');
let network = null;
let utils = null;
let api = null;
const app = getApp();
// var start0 = 0;
// var start1 = 0;
// var start2 = 0;
// var start4 = 0;
// var start5 = 0;
// var start6 = 0;

Page(Object.assign({}, Zan.Tab, Zan.TopTips, Zan.Toast, {

  /**
   * 页面的初始数据
   * 订单状态 1=待付款， 2=待发货，3=待收货，4=已完成，5=已失效，6=售后，7=已消费，8=未消费，9=拼团中
   * 类型  0=线上订单 1=线下订单'
   */
  data: {
    tab: {
      list: [{
        id: 0,
        title: '全部'
      }, {
        id: 1,
        title: '待付款'
      }, {
        id: 2,
        title: '进行中'
      }, {
        id: 4,
        title: '已完成'
      }, {
        id: 5,
        title: '已失效'
      }, {
        id: 6,
        title: '售后'
      }],
      selectedId: 0,
      height: 45,
      scroll: true
    },
    delOrderId: "",
    endOrderId: "",
    allOrder: [],
    order01: [],
    order02: [],
    order03: [],
    order04: [],
    order05: [],
    activeIndex: 0,
    hideStatus: true,
    store: null,
    recordsTotal:0,
    start0: 0,
    start1: 0,
    start2: 0,
    start4: 0,
    start5: 0,
    start6: 0,
    nodata: {
      msg: '无相关数据',
      notype: 1,
      imgurl: '../../../images/nodatas.png',
      nourl: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();

    
    this.data.tab.selectedId = options.index;
    this.setData({
      tab: this.data.tab,
      store: app.globalData.store
    })
    this.setData({
      activeIndex: options.index
    })
    
    this.onPullDownRefresh();
    

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    loadData(this, this.data.tab.selectedId);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
    if (this.data.tab.selectedId == 0) {
      wx.showLoading();
      if (this.data.allOrder.length < this.data.recordsTotal) {
        this.setData({
          start0: this.data.start0 + 20
        })
        // console.log("start0------------" + this.data.start0);
        // console.log("recordsTotal------------" + this.data.recordsTotal);
        network._post_page_json(this, api.getOrder, this.data.start0, { status: this.data.tab.selectedId, storeId: this.data.store.id }, orderSuccess);
      } else {
        wx.hideLoading();
      }
    } else if (this.data.tab.selectedId == 1) {
      wx.showLoading();
      if (this.data.order01.length < this.data.recordsTotal) {
        this.setData({
          start1: this.data.start1 + 20
        })
        // console.log("start1------------" + this.data.start1);
        // console.log("recordsTotal------------" + this.data.recordsTotal);
        network._post_page_json(this, api.getOrder, this.data.start1, { status: this.data.tab.selectedId, storeId: this.data.store.id }, orderSuccess);
      } else {
        wx.hideLoading();
      }
    } else if (this.data.tab.selectedId == 2) {
      wx.showLoading();
      if (this.data.order02.length < this.data.recordsTotal) {
        this.setData({
          start2: this.data.start2 + 20
        })
        // console.log("start2------------" + this.data.start2);
        network._post_page_json(this, api.getOrder, this.data.start2, { status: this.data.tab.selectedId, storeId: this.data.store.id }, orderSuccess);
      } else {
        wx.hideLoading();
      }
    } else if (this.data.tab.selectedId == 4) {
      wx.showLoading();
      if (this.data.order03.length < this.data.recordsTotal) {
        this.setData({
          start4: this.data.start4 + 20
        })
        // console.log("start4------------" + this.data.start4);
        network._post_page_json(this, api.getOrder, this.data.start4, { status: this.data.tab.selectedId, storeId: this.data.store.id }, orderSuccess);
      } else {
        wx.hideLoading();
      }
    } else if (this.data.tab.selectedId == 5) {
      wx.showLoading();
      if (this.data.order04.length < this.data.recordsTotal) {
        this.setData({
          start5: this.data.start5 + 20
        })
        // console.log("start5------------" + this.data.start5);
        network._post_page_json(this, api.getOrder, this.data.start5, { status: this.data.tab.selectedId, storeId: this.data.store.id }, orderSuccess);
      } else {
        wx.hideLoading();
      }
    } else if (this.data.tab.selectedId == 6) {
      wx.showLoading();
      
      if (this.data.order05.length < this.data.recordsTotal) {
        console.log(this.data.order05.length);
        this.setData({
          start6: this.data.start6 + 20
        })
        // console.log("start6------------" + this.data.start6);
        // console.log("recordsTotal------------" + this.data.recordsTotal);
        network._post_page_json(this, api.getOrder, this.data.start6, { status: this.data.tab.selectedId, storeId: this.data.store.id }, orderSuccess);
      } else {
        wx.hideLoading();
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },

  handleZanTabChange(e) {
    var componentId = e.componentId;
    var selectedId = e.selectedId;

    this.setData({
      [`${componentId}.selectedId`]: selectedId
    });


    this.setData({
      activeIndex: selectedId
    })

    loadData(this, this.data.tab.selectedId);
  },

  // 取消订单
  cancel: function (e) {
    var orderId = e.currentTarget.dataset.id;

    this.setData({
      delOrderId: orderId
    })
    var that = this
    wx.showModal({
      title: '提示',
      content: '确定取消该订单吗？',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          network._post_json(that, api.delOrder, { id: orderId }, success);
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },

  // 确认收货
  endOrder: function (e) {
    var orderId = e.currentTarget.dataset.item.id;
    console.log(orderId);
    this.setData({
      endOrderId: orderId
    })
    network._post_json(this, api.endOrder, { id: orderId }, endSuccess);
  },

  // 购买
  pay: function (e) {
    var item = e.currentTarget.dataset.item;

    let order = {};
    order.orderId = item.id;
    order.orderNO = item.orderNo;
    if (item.oldMemberPrice != "0"){
      order.couponPrice = item.oldMemberPrice;
      order.totalPrice = parseInt(item.total) + parseInt(item.oldMemberPrice);
    } else if (item.oldSaleMoney != "0"){
      order.couponPrice = item.oldSaleMoney;
      order.totalPrice = parseInt(item.total) + parseInt(item.oldSaleMoney);
    }else{
      order.couponPrice = "0";
      order.totalPrice = item.total;
    }
    wx.navigateTo({
      url: '/pages/pay/ChoosePay?order=' + JSON.stringify(order) + '&store=' + encodeURIComponent(JSON.stringify(this.data.store))
    })

  },

  /**
  * 拨打电话
  */
  call: function (e) {
    /**
    * 获取商家电话
    */
    if (app.globalData.userAndTenantInfo) {
      wx.makePhoneCall({
        phoneNumber: app.globalData.userAndTenantInfo.tenant.phone
      })
    } else {
      app.userInfoCallback = res => {
        this.setData({
          tenant: res.tenant
        })
      }
    }
  },
  //售后
  shouhouTk: function (e) {
    order.shouhouTk(0, e);

  },

  //售后处理
  Agreeaftersale: function (e) {
    var order = e.currentTarget.dataset.order;
    if (order.product[0].productSpec) {
      var productprice = order.product[0].productSpec.price;
      var pspec = order.product[0].productSpec.name
    } else {
      var productprice = order.product[0].price
    }
    var saleMoney = order.oldSaleMoney;
    var integralPrice = order.oldIntegralPrice;
    var ordertotal = order.oldTotal + saleMoney + integralPrice;
    var refund_fee = order.product[0].refundOrder.refund_fee;
    if (order.product[0].applicationBack.type == 1) {
      var ordertype = '已经发货'
    } else {
      var ordertype = '未发货'
    }
    if (order.product[0].refundOrder.status == 0) {
      var Refundresults = '同意退款'
    } else if (order.product[0].refundOrder.status == 1) {
      var Refundresults = '拒绝售后，请联系商家'
    } else if (order.product[0].refundOrder.status == 2) {
      var Refundresults = '退款成功'
    } else if (order.product[0].refundOrder.status == 4) {
      var Refundresults = '正在处理售后，请等待'
    }
    var createDate = utils.formatDate(new Date(order.product[0].refundOrder.createDate));
    if (order.product[0].refundOrder.endDate != null) {
      var endDate = utils.formatDate(new Date(order.product[0].refundOrder.endDate));
    } else {
      var endDate = order.product[0].refundOrder.endDate
    }
    var getdata = {
      'productimg': order.product[0].smallImgUrl,
      'producttitle': order.product[0].title,
      'productspec': pspec,
      'productprice': productprice,
      'productcount': order.product[0].count,
      'agreeafterprice': refund_fee,
      'tuikuan': ordertype,
      'tuikuanwhy': order.product[0].applicationBack.reason,
      'tuikuancontent': order.product[0].applicationBack.refund_content,
      'tuikuanresults': Refundresults,
      'istongyi': order.product[0].refundOrder.status,
      'isfahuo': order.product[0].applicationBack.type,
      'tuihuoorderid': order.product[0].refundOrder.id,
      'expressName': order.product[0].refundOrder.expressName,
      'expressNo': order.product[0].refundOrder.expressNo,
      'createdate': createDate,
      'enddate': endDate,
      'out_refund_no': order.product[0].refundOrder.out_refund_no,
      'ordertotal': ordertotal,
      'maijialiu': order.product[0].refundOrder.content,
      'ordertype': order.type,
      'tyueyouhui': productprice * order.product[0].count - refund_fee
    }
    wx.setStorageSync('neworder', getdata)
    if (order.product[0].refundOrder.status == 0 || order.product[0].refundOrder.status == 4 || order.product[0].refundOrder.status == 1) {
      wx.navigateTo({
        url: '/pages/myself/order/shouhou/waitingSale',
      })
    } else if (order.product[0].refundOrder.status == 2) {
      wx.navigateTo({
        url: '/pages/myself/order/shouhou/refunded',
      })
    }

  },

  refresh: function () {
    this.onPullDownRefresh();
  },
  scan: function (e) {
    var orderId = e.currentTarget.dataset.item.id;
    console.log(orderId);
    // 只允许从相机扫码
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        console.log(res);
        if (res.path) {
          let scene = decodeURIComponent(res.path);
          let index = scene.indexOf('scene=');
          if (index == -1) {
            this.showZanTopTips(this.error, '无效门店二维码！');
          } else {
            var scene = decodeURIComponent(res.path);
            var index = scene.indexOf('scene=')
            network._post_json(this, api.end, { orderId: orderId, storeId: scene.substring(index + 6, scene.length) }, scanSuccess);
          }

        } else if (res.result == "") {
          this.showZanTopTips(this.error, '无效门店二维码！');
        } else if (res.result == "*") {
          this.showZanTopTips(this.error, '无效门店二维码！');
        } else {
          this.showZanTopTips(this.error, '无效门店二维码！');
        }
      }
    })
  }
  
}))

/**
 * 加载数据
 */
var loadData = function (that, index) {
  that.setData({
    start0: 0,
    start1: 0,
    start2: 0,
    start4: 0,
    start5: 0,
    start6: 0,
  })
  wx.showLoading();
  if (index == 0) {
    that.setData({
      allOrder: [],
    });
    network._post_page_json(that, api.getOrder, that.data.start0, { status: index, storeId: that.data.store.id }, orderSuccess);
  } else if (index == 1) {
    that.setData({
      order01: [],
    });
    network._post_page_json(that, api.getOrder, that.data.start1, { status: index, storeId: that.data.store.id }, orderSuccess);
  } else if (index == 2) {
    that.setData({
      order02: [],
    });
    network._post_page_json(that, api.getOrder, that.data.start2, { status: index, storeId: that.data.store.id }, orderSuccess);
  } else if (index == 4) {
    that.setData({
      order03: [],
    });
    network._post_page_json(that, api.getOrder, that.data.start4, { status: index, storeId: that.data.store.id }, orderSuccess);
  } else if (index == 5) {
    that.setData({
      order04: [],
    });
    network._post_page_json(that, api.getOrder, that.data.start5, { status: index, storeId: that.data.store.id }, orderSuccess);
  } else if (index == 6) {
    that.setData({
      order05: [],
    });
    network._post_page_json(that, api.getOrder, that.data.start6, { status: index, storeId: that.data.store.id }, orderSuccess);
  }
  
}

// 获取订单列表结果
var orderSuccess = function (that, res) {
  if (that.data.tab.selectedId == 0) {
    that.setData({
      allOrder: that.data.allOrder.concat(res.data.data),
      recordsTotal: res.data.count
    });
  } else if (that.data.tab.selectedId == 1) {
    that.setData({
      order01: that.data.order01.concat(res.data.data),
      recordsTotal: res.data.count
    });
  } else if (that.data.tab.selectedId == 2) {
    that.setData({
      order02: that.data.order02.concat(res.data.data),
      recordsTotal: res.data.count
    });
  } else if (that.data.tab.selectedId == 4) {
    that.setData({
      order03: that.data.order03.concat(res.data.data),
      recordsTotal: res.data.count
    });
  } else if (that.data.tab.selectedId == 5) {
    that.setData({
      order04: that.data.order04.concat(res.data.data),
      recordsTotal: res.data.count
    });
  } else if (that.data.tab.selectedId == 6) {
    that.setData({
      order05: that.data.order05.concat(res.data.data),
      recordsTotal: res.data.count
    });
  }
  wx.hideLoading();
}

// 取消订单
var success = function (that, res) {
  if (that.data.tab.selectedId == 0) {
    that.setData({
      allOrder: Array.prototype.remove(that.data.allOrder, that.data.delOrderId)
    })
  } else if (that.data.tab.selectedId == 1) {
    that.setData({
      order01: Array.prototype.remove(that.data.order01, that.data.delOrderId)
    })
  } else if (that.data.tab.selectedId == 2) {
    that.setData({
      order02: Array.prototype.remove(that.data.order02, that.data.delOrderId)
    })
  } else if (that.data.tab.selectedId == 3) {
    that.setData({
      order03: Array.prototype.remove(that.data.order03, that.data.delOrderId)
    })
  } else if (that.data.tab.selectedId == 4) {
    that.setData({
      order04: Array.prototype.remove(that.data.order04, that.data.delOrderId)
    })
  }

  that.showZanToast('订单取消成功');
  var timer = setTimeout(that.refresh,1500);
}

var endSuccess = function (that, res) {
  
  //if (res.data.data) {
  // that.setData({
  //   order03: Array.prototype.remove(that.data.order03, that.data.endOrderId)
  // });
  that.showZanToast('收货成功');
  var timer = setTimeout(that.refresh, 1500);
  //}
}
var scanSuccess = function(that,res){
  that.showZanToast('确认消费成功');
  var timer = setTimeout(that.refresh, 1500);
}
Array.prototype.remove = function (order, id) {
  for (var i = 0; i < order.length; i++) {
    if (order[i].id == id) {
      order.splice(i, 1);
    }
  }
  return order;
}